package exceptionhandler;

import commomresult.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 实现全局的Controller层的异常处理
 * 优点:将Controller层的异常和数据校验异常进行统一处理,减少模板代码,减少代码量,提高扩展性和可维护性
 * 缺点:只能处理Controller层未捕获的异常,对于Interceptor层的异常,Spring框架层的异常,无能为力
 * @author gaofeng
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    CommonResult<String> handlerException(Exception e) {
//        log.error(e.getMessage(), e);
        CommonResult<String> commonResult = new CommonResult<>() ;
        commonResult.setMsg("操作失败!");
        return commonResult ;
    }

    /**
     * 处理所有的业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    CommonResult<String> handlerBusinessException(BusinessException e) {
//        log.error(e.getMessage(), e);
        CommonResult<String> commonResult = new CommonResult<>() ;
        commonResult.setMsg("操作失败!");
        return commonResult ;
    }

    /**
     * 处理所有接口的参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    CommonResult<String> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
//        log.error(e.getMessage(), e);
        CommonResult<String> commonResult = new CommonResult<>() ;
        commonResult.setMsg(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return commonResult ;
    }
}
